<?php
//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//
//         .............................................
//                  佛祖镇楼                  BUG退散

namespace app\tool;


use app\LogHelper;
use Luler\Helpers\MultiProcessHelper;
use think\facade\Cache;

class LaravelLogTool
{
    /**
     * 推送laravel日志
     * @throws \Exception
     * @author 我只想看看蓝天 <1207032539@qq.com>
     */
    public static function work()
    {
        $base_path = config('app.laravel.path');
        $files = CommonTool::getAllFiles($base_path);
        $files = array_filter($files, function ($value) {
            if (preg_match('/\.log$/', $value)) {
                return true;
            }
            return false;
        });

        foreach ($files as $file) {
            MultiProcessHelper::instance()->multiProcessTask(function () use ($file) {
                $cache_key = 'LaravelLogTool:work:' . md5($file);
                $since_count = Cache::get($cache_key) ?: 0;
                $handle = fopen($file, 'r');
                $i = 0;
                $message = [];
                $create_time = '';
                $level = LogHelper::$level_info;
                $data = [];
                while (!feof($handle)) {
                    $line = fgets($handle);
                    if ($line === false) {
                        continue;
                    }
                    $i++;
                    if ($since_count >= $i) {
                        continue;
                    }
                    if (preg_match('/^\[([\d:\-\s]+)\]/', $line, $match)) {
                        //存在消息，先提交，在进入下一轮数据采集
                        if (!empty($message) && !empty($create_time)) {
                            $data[] = [
                                'level' => $level,
                                'client_ip' => '0.0.0.0',
                                'message' => join($message),
                                'other' => $file,
                                'create_time' => $create_time,
                                'url' => '-',
                                'waste_time' => 0,
                                'code' => '',
                            ];
                            $message = [];
                        }
                        $create_time = $match[1];
                        preg_match('/\.([A-Z]+):/', $line, $match);
                        $level = isset($match[1]) ? (in_array($match[1], ['ERROR', 'INFO']) ? strtolower($match[1]) : LogHelper::$level_warning) : LogHelper::$level_info;
                    }
                    $message[] = $line;
                    if (count($data) >= 100) {
                        LogHelper::instance()->saveLog($data);
                        Cache::set($cache_key, $i); //成功清洗，才记录行数
                        $data = [];
                    }
                }
                //遍历完文件，防止遗漏
                if (!empty($message) && !empty($create_time)) {
                    $data[] = [
                        'level' => $level,
                        'client_ip' => '0.0.0.0',
                        'message' => join($message),
                        'other' => $file,
                        'create_time' => $create_time,
                        'url' => '-',
                        'waste_time' => 0,
                        'code' => '',
                    ];
                }
                if (!empty($data)) {
                    LogHelper::instance()->saveLog($data);
                    Cache::set($cache_key, $i); //成功清洗，才记录行数
                }
                fclose($handle);
            });
        }
    }
}